<?php
namespace Admin\Controller;
use Think\Controller;
use \Think\Page;
use \Think\Model;
class UserController extends CommonController {
	//会员列表
	public function index($num='',$username='',$userid='',$truename='',$user_type=''){
		if(empty($num)){
			$num = 10;
		}
		
		$m = M('users');
		
		if(!empty($username)){
			$count = $m -> where('user_name = "%s"',[$username]) -> count();
			$Page = new Page($count,$num);
			$show = $Page -> show();
			$res = $m -> field('user_id,user_name,name,true_name,inviter_id,tree_id,report_user_id,
					user_money1,user_money2,user_money3,user_money4,user_money,cishan_money,dongtaikoushui_money,is_reportcenter,
					pay_points1,pay_points2,pay_points3,pay_points4,pay_points5,option_num,left_num,right_num,is_out,reg_time,is_jh') -> 
					join('zx_user_type on zx_users.user_type = zx_user_type.id') -> 
					where(['user_name'=>$username]) -> order('reg_time desc') -> limit($Page->firstRow.','.$Page->listRows) -> select();

		}elseif(!empty($userid)){
			$count = $m -> where('user_id= "%s" ',[$userid]) -> count();
			$Page = new Page($count,$num);
			$show = $Page -> show();
			$res = $m -> field('user_id,user_name,name,true_name,inviter_id,tree_id,report_user_id,
					user_money1,user_money2,user_money3,user_money4,user_money,cishan_money,dongtaikoushui_money,is_reportcenter,
					pay_points1,pay_points2,pay_points3,pay_points4,pay_points5,option_num,left_num,right_num,is_out,reg_time,is_jh') -> 
					join('zx_user_type on zx_users.user_type = zx_user_type.id') -> 
					where(['user_id'=>$userid]) -> order('reg_time desc') -> limit($Page->firstRow.','.$Page->listRows) -> select();
		}elseif(!empty($truename)){
			$count = $m -> where('true_name= "%s"',[$truename]) -> count();
			$Page = new Page($count,$num);
			$show = $Page -> show();
			$res = $m -> field('user_id,user_name,name,true_name,inviter_id,tree_id,report_user_id,
					user_money1,user_money2,user_money3,user_money4,user_money,cishan_money,dongtaikoushui_money,is_reportcenter,
					pay_points1,pay_points2,pay_points3,pay_points4,pay_points5,option_num,left_num,right_num,is_out,reg_time,is_jh') -> 
					join('zx_user_type on zx_users.user_type = zx_user_type.id') -> 
					where(['true_name'=>$truename]) -> order('reg_time desc') -> limit($Page->firstRow.','.$Page->listRows) -> select();
		}elseif(!empty($user_type)){
			$count = $m -> where('user_type= "%s"',[$user_type]) -> count();
			$Page = new Page($count,$num);
			$show = $Page -> show();
			$res = $m -> field('user_id,user_name,name,true_name,inviter_id,tree_id,report_user_id,
					user_money1,user_money2,user_money3,user_money4,user_money,cishan_money,dongtaikoushui_money,is_reportcenter,
					pay_points1,pay_points2,pay_points3,pay_points4,pay_points5,option_num,left_num,right_num,is_out,reg_time,is_jh') -> 
					join('zx_user_type on zx_users.user_type = zx_user_type.id') -> 
					where('user_type= "%s"',[$user_type]) -> order('reg_time desc') -> limit($Page->firstRow.','.$Page->listRows) -> select();
		}else{		
			$count = $m -> count();
			$Page = new Page($count,$num);
			$show = $Page -> show();
			$res = $m -> field('user_id,user_name,name,true_name,inviter_id,tree_id,report_user_id,
				user_money1,user_money2,user_money3,user_money4,user_money,cishan_money,dongtaikoushui_money,is_reportcenter,
				pay_points1,pay_points2,pay_points3,pay_points4,pay_points5,option_num,left_num,right_num,is_out,reg_time,is_jh') -> 
				join('zx_user_type on zx_users.user_type = zx_user_type.id') -> 
				order('reg_time desc') -> limit($Page->firstRow.','.$Page->listRows) -> select();

		}
		// echo M() -> _SQL();
		// dump($res);
		$this -> assign('num',$num);
		$this -> assign('url',$show);
		$this -> assign('count',$count);
		foreach($res as $k=>$v){
			if($v['left_num']>=$v['right_num']){
				$res[$k]['left_num']=$v['right_num'];
			}
		}
		$this -> assign('res',$res);
		$this -> display('user/index');
	}

	//会员级别
	public function jibie(){
		$res = M('user_type') -> select();
		$this -> assign('jibie',$res);
		$this -> display();
	}

	//会员升级操作
	public function shengjihuiyuan(){
		if(I('post.id') == 0){
			$this -> error('请先选择升级级别');
		}else{
		
			$mod = M('user_type');
			$mod -> startTrans();
			$data = $mod -> where('id=%d',[I('post.id')]) -> find();
			$is_reg = $data['is_reg'];
		
				$m3 = M('admin_log');
				//封装后台日志					
					$ad_log['user_name'] = $_SESSION['admin']['user_name'];
					$ad_log['log_time'] = time();
					$ad_log['user_id'] = $_SESSION['admin']['user_id'];
					$ad_log['log_info'] = '升级会员级别操作';
					$ad_log['ip_address']= get_client_ip();
					$res3 = $m3 -> add($ad_log);
				$data1 = ['user_type' => I('post.id')];
				$res = M('users') -> data($data1) -> where('user_type=%d',[I('post.tid')]) -> save();
				
				if($res>0 && $res3>0) {
					$mod -> commit();
					$this -> success('全部相关会员已升级');
				}else{
					$mod -> rollback();
					$this -> error('升级失败');
				}
			
		}
	}

	//会员级别修改参数
	public function edit(){
		$data[I('post.name')] = I('post.shuju');
		$res = M('user_type') -> data($data) -> where('id=%d',[I('post.id')]) -> save();
		if($res){
			echo I('post.shuju');
		}else{
			echo '';
		}
	}

	//切换是否开启该会员级别
	public function edit1(){
		if(I('post.is_reg') == 1){
			$is_reg = 0;
		}elseif($is_reg == 0){
			$is_reg = 1;
		}
		$res = M('user_type') -> data(['is_reg'=>$is_reg]) -> where('id=%d',[I('post.id')]) ->  save();
		if($res){
			echo 1;
		}else{
			echo 0;
		}
	}
	//账户冻结
	public function dongjie(){
		$id = I('get.aa');
		$users = M('users') -> where('user_id = "%d"',$id) ->find();
		$users['is_jh'] = '1';
		$mod = M('users');
		$mod -> startTrans();
		$res = $mod -> where('user_id = "%d"',$id) -> data($users) ->save();
		$m3 = M('admin_log');
		//封装后台日志					
			$ad_log['user_name'] = $_SESSION['admin']['user_name'];
			$ad_log['log_time'] = time();
			$ad_log['user_id'] = $_SESSION['admin']['user_id'];
			$ad_log['log_info'] = '冻结会员'.I('post.user_name');
			$ad_log['ip_address']= get_client_ip();
			$res3 = $m3 -> add($ad_log);
		if($res>0 && $res3>0){
			$mod -> commit();
			$this -> success('冻结成功',U('admin/user/index'));
		}else{
			$mod -> rollback();
			$this -> error('冻结失败',U('admin/user/index'));
		}
	}
	//解冻
	public function jiedong(){
		$id = I('get.aa');
		$mod = M('users');
		$mod -> startTrans();
		$users = $mod -> where('user_id = "%d"',$id) ->find();
		$users['is_jh'] = '0';
		$res = M('users') -> where('user_id = "%d"',$id) -> data($users) ->save();
		//封装日志		
			$m3 = M('admin_log');		
			$ad_log['user_name'] = $_SESSION['admin']['user_name'];
			$ad_log['log_time'] = time();
			$ad_log['user_id'] = $_SESSION['admin']['user_id'];
			$ad_log['log_info'] = '解冻会员'.I('post.user_name').'账户';
			$ad_log['ip_address']= get_client_ip();
			$res3 = $m3 -> add($ad_log);
		if($res>0 && $res3>0){
			$mod -> commit();
			$this -> success('解冻成功',U('admin/user/index'));
		}else{
			$mod -> rollback();
			$this -> error('解冻失败',U('admin/user/index'));
		}
	} 
	//会员列表查看相关人的推荐人、接点人、报单中心
	public function chakan(){
		$data['inviter'] = M('users') -> field('user_id,user_name,true_name') -> where('user_id=%d',[I('get.bb')]) -> find();
		$data['user'] = M('users') -> field('user_id,user_name,true_name') -> where('user_id=%d',[I('get.aa')]) -> find();
		$data['tree'] = M('users') -> field('user_id,user_name,true_name') -> where('user_id=%d',[I('get.cc')]) -> find();
		$data['report'] = M('users') -> field('user_id,user_name,true_name') -> where('user_id=%d',[I('get.dd')]) -> find();
		$this -> assign('data',$data);
		$this -> display();
	}

	//会员信息编辑修改界面
	public function bianji(){
		$res = M('users') -> field('user_money1,user_money2,user_name,inviter_id,true_name,cardno,mobile_phone,address,mainbank,bank_name,bank_code,bank_user,zhifubao,weixin,user_type') -> where('user_id=%d',[I('get.aa')]) -> find();
		$this -> assign('user_id',I('get.aa'));
		$this -> assign('res',$res);
		$this -> display();
	}

	//会员信息修改操作
	public function xiugai(){
		$mod = M('users');
		$user = I('post.');
		
		$mod -> startTrans();
		$user_money = $mod ->field('user_money1,user_money2')->where('user_id= "%d"',I('get.id'))->find();
		if(!empty($user['password'])){
			if($user['password']!=$user['password1']||$user['repassword']!=$user['repassword1']){
							$this -> error('两次密码或安全码不同');
			}else{
							unset($user['password1']);
							unset($user['repassword1']);					
							$user['repassword'] = md5($user['repassword']);			
							$user['ec_salt'] = rand('1111','9999');
							$user['password'] = md5(md5($user['password']).$user['ec_salt']);
							if($user_money['user_money1']>=20){
								$user['user_money1'] = $user_money['user_money1']-20;
							}else{
								$user['user_money2'] = $user_money['user_money2']-20;
							}			
			}

		}else{
					unset($user['password']);
					unset($user['password1']);
					unset($user['repassword']);
					unset($user['repassword1']);
					if($user_money['user_money1']>=20){
								$user['user_money1'] = $user_money['user_money1']-20;
							}else{
								$user['user_money2'] = $user_money['user_money2']-20;
							}	
		}	
			
		$res = $mod -> where('user_id= "%d"',I('get.id'))->save($user);
		$m3 = M('admin_log');
		//封装日志			
			$ad_log['user_name'] = $_SESSION['admin']['user_name'];
			$ad_log['log_time'] = time();
			$ad_log['user_id'] = $_SESSION['admin']['user_id'];
			$ad_log['log_info'] = '修改会员'.I('post.user_name').'基本信息';
			$ad_log['ip_address']= get_client_ip();
			$res3 = $m3 -> add($ad_log);
		if($res>0 &&$res3>0){
				$mod -> commit();
				$this -> success('会员信息修改成功',U('admin/user/index'));
		}else{
				$mod -> rollback();
				$this -> error('会员信息修改失败',U('admin/user/index'));
		}
	}



	//保单中心切换ajax
	public function baodan(){
		if(I('post.is_reportcenter') == '1'){
			$data = ['is_reportcenter' => '0'];
			$res = M('users') -> data($data) -> where('user_id=%d',[I('post.user_id')]) ->save();
		}elseif(I('post.is_reportcenter') == '0'){
			$data = ['is_reportcenter' => '1'];
			$res = M('users') -> data($data) -> where('user_id=%d',[I('post.user_id')]) ->save();
		}
		if($res){
			echo 1;
		}else{
			echo 0;
		}
	}

	//会员列表明细列表
	public function mingxi(){
		$res = M('users') -> field('sum(user_money1) as money1,sum(user_money2) as money2,sum(user_money4) as money4,sum(option_num) as option_num,sum(cishan_money) as cishan_money,sum(dongtaikoushui_money) as dtks,sum(pay_points1) as points1,sum(pay_points2) as points2,sum(pay_points3) as points3,sum(pay_points4) as points4,sum(pay_points5) as points5') -> where('user_id=%d',[I('get.aa')]) -> find();
		$res1 = M('account_log') -> field('log_id,change_time,change_desc,user_money1,user_money2,user_money3,user_money4,cishan_money,dongtaikoushui_money,pay_points1,pay_points2,pay_points3,pay_points4,pay_points5,option_num,about_user_name') -> where('user_id=%d',[I('get.aa')]) -> order('change_time desc') -> select();
		$this -> assign('user_name',I('get.bb'));
		$this -> assign('user_id',I('get.aa'));
		$this -> assign('res',$res);
		$this -> assign('res1',$res1);
		$this -> display();
	}

	//调节会员账户
	public function tiaojie(){
		$res = M('users') -> field('user_money1,user_money2,user_money3,user_money4,option_num') -> where('user_id=%d',[I('get.user_id')]) -> find();
		$this -> assign('user_name',I('get.user_name'));
		$this -> assign('user_id',I('get.user_id'));
		$this -> assign('res',$res);
		$this -> display();
	}

	//账户调节操作
	public function update(){

		$user_money1 = I('post.hao1') * I('post.user_money1');
		$user_money2 = I('post.hao2') * I('post.user_money2');
		$user_money3 = I('post.hao3') * I('post.user_money3');
		$user_money4 = I('post.hao4') * I('post.user_money4');
		$option_num = I('post.hao5') * I('post.option_num');
		$change_desc = I('post.change_desc');
		$user_id = I('post.user_id');
		$data = ['change_desc' => $change_desc,'user_money1' => $user_money1,'user_money2' => $user_money2,'user_money3' => $user_money3,'user_money4' => $user_money4,'option_num' => $option_num,'change_time' => time(),'user_id' => $user_id];

		$m1 = M('users');
		$m2 = M('account_log');
		$m3 = M('admin_log');

		//封装日志			
			$ad_log['user_name'] = $_SESSION['admin']['user_name'];
			// dump($ad_log);die;
			$ad_log['log_time'] = time();
			$ad_log['user_id'] = $_SESSION['admin']['user_id'];
			$ad_log['log_info'] = '调节会员'.I('post.user_name').'账户信息';
			$ad_log['ip_address']= get_client_ip();
			$res3 = $m3 ->data($ad_log)-> add();
			
		$m1 -> startTrans();
		$res1 = $m1 -> execute('update zx_users set user_money1=user_money1+'.$user_money1.',user_money2=user_money2+'.$user_money2.',user_money3=user_money3+'.$user_money3.',user_money4=user_money4+'.$user_money4.',option_num=option_num+'.$option_num.' where user_id='.$user_id);
		
		if($res1){
			$res2 = $m2 -> data($data) -> where('user_id=%d' ,[$user_id]) -> add();
			// dump($res2);die;
			if($res2>0&&$res3>0){
				
				$this -> success('调节成功',U('/admin/user/mingxi?aa='.$user_id.'&bb='.I('post.user_name')));
			}else{
				$this -> error('调节失败(可能为写入日志失败)');
				$m1 -> rollback();
			}
			$m1 -> commit();
		}else{
			$m1 -> rollback();
			$this -> error('调节失败');
		}
	}


	//组织结构图
	public function organization($user_name=''){
		if(empty($user_name)){
			$this -> error('没有该用户');
				$user_name = '001';	
				$level1 = M('users') -> field('user_id,user_name,tree_num,true_name,left_num,right_num,left_leave_amount,right_leave_amount') -> where('user_name=%d',[$user_name]) -> find();
		}else{
			$res = M('users') -> where(['user_name'=>$user_name]) -> find();
			if(!$res){
				$this -> error('没有该用户');
			}
			if($user_name == '001'){
				$level1 = M('users') -> field('user_id,user_name,tree_num,true_name,left_num,right_num,left_leave_amount,right_leave_amount') -> where('user_name=%d',[$user_name]) -> find();
			}else{
				$level1 = M('users') -> field('tree_id,user_id,user_name,name,tree_num,true_name,left_num,right_num,left_leave_amount,right_leave_amount') -> join('zx_user_type on zx_users.user_type = zx_user_type.id') -> where(['user_name'=>$user_name]) -> find();
				$tree = M('users') -> field('user_name') -> where(['user_id'=>$level1['tree_id']]) -> find();
			}
		}
		$arr = M('users') -> field('user_id,user_name,name,tree_num,true_name,left_num,right_num,left_leave_amount,right_leave_amount,tree_left_code,tree_right_code') -> join('zx_user_type on zx_users.user_type = zx_user_type.id') -> where(['tree_id'=>$level1['user_id']]) -> select();
		// $l2 = M() -> query('select user_id user_name,tree_num,true_name,left_num,right_num,left_leave_amount,right_leave_amount,tree_left_code,tree_right_code where in');
		$res = strpos($arr[0]['tree_left_code'],$level1['user_id']);
		$res2 = strpos($arr[0]['tree_right_code'],$level1['user_id']);
		if($res>-1){
			$l2 = $arr[0];
			$r2 = $arr[1];
		}elseif($res2>-1){
			$r2 = $arr[0];
			$l2 = $arr[1];
		}
		$arr1 = M('users') -> field('user_id,user_name,name,tree_num,true_name,left_num,right_num,left_leave_amount,right_leave_amount,tree_left_code,tree_right_code') -> join('zx_user_type on zx_users.user_type = zx_user_type.id') -> where(['tree_id'=>$l2['user_id']]) -> order('reg_time') -> select();
		$arr2 = M('users') -> field('user_id,user_name,name,tree_num,true_name,left_num,right_num,left_leave_amount,right_leave_amount,tree_left_code,tree_right_code') -> join('zx_user_type on zx_users.user_type = zx_user_type.id') -> where(['tree_id'=>$r2['user_id']]) -> order('reg_time') -> select();

		$res3 = strpos($arr1[0]['tree_left_code'],$l2['user_id']);
		$res4 = strpos($arr1[0]['tree_right_code'],$l2['user_id']);
		if($res3>-1){
			$l21 = $arr1[0];
			$l22 = $arr1[1];
		}elseif($res4>-1){
			$l22 = $arr1[0];
			$l21 = $arr1[1];
		}

		$res4 = strpos($arr2[0]['tree_left_code'],$r2['user_id']);
		$res5 = strpos($arr2[0]['tree_right_code'],$r2['user_id']);
		if($res4>-1){
			$r21 = $arr2[0];
			$r22 = $arr2[1];
		}elseif($res5>-1){
			$r22 = $arr2[0];
			$r21 = $arr2[1];
		}

		$this -> assign('tree',$tree['user_name']);
		$this -> assign('level1',$level1);
		$this -> assign('l2',$l2);
		$this -> assign('r2',$r2);
		$this -> assign('l21',$l21);
		$this -> assign('l22',$l22);
		$this -> assign('r21',$r21);
		$this -> assign('r22',$r22);
		$this -> display();
	}

	//匹配认购积分
	public function pprg(){
		//待匹配人数
		$count = M('users') -> where(['user_money3'=>['gt',0]]) -> order('huitian_time') -> count();
		//分页
		$Page = new Page($count,50);
		$show = $Page -> show();
		//认购积分总数
		$peo = M('users') -> field('sum(user_money3) as user_money3') -> find();
		//当前剩余积分数量
		$mod = new Model();
		$price = $mod -> query('select points_num1 from zx_k_log where k_id=(select max(k_id) from zx_k_log)');
		$points_num1 = $price[0]['points_num1'];
		//预计和涨价
		$res2 = M('param') -> field('param1,param8_2') -> where('id=%d',[1]) -> find();
		$tishi = $res2['param1']*$points_num1;
		$zhangjia = $res2['param8_2'];
		//市场剩余e积分数量
		$market = M('market') -> field('sum(sell_num) as sell_num') -> where(['change_type'=>'option_num','status'=>0]) -> find();
		//市场累计出售e积分总数量
		$all = M('market') -> field('sum(sell_num) as sell_num') -> where(['change_type'=>'option_num','status'=>3,'sell_user_id'=>['neq',0]]) -> find();
		$s_all = $all['sell_num'];

		//查找待匹配人
		$res = M('users') -> field('user_name,user_money3,reg_time') -> where(['user_money3'=>['gt',0]]) -> order('huitian_time') -> limit($Page->firstRow.','.$Page->listRows) -> select();
		$this -> assign('tishi',$tishi);
		$this -> assign('market',$market);
		$this -> assign('points_num1',$points_num1);
		$this -> assign('zhangjia',$zhangjia);
		$this -> assign('peo',$peo);
		$this -> assign('gujia',$res2['param1']);
		$this -> assign('url',$show);
		$this -> assign('count',$count);
		$this -> assign('res',$res);
		$this -> assign('s_all',$s_all);
		$this -> display();
	}

	//匹配认购积分
	public function actrgjf(){
		//实例化Model
		$m = M('users');
		//查出认购积分大于0的人
		$res = $m -> field('user_id,user_money3,option_num,max_amount') -> join('zx_user_type on zx_users.reg_type=zx_user_type.id') -> where(['user_money3'=>['gt',0]]) -> order('huitian_time') -> limit(0,I('post.renshu')) -> select();
		//开启事务
		$m -> startTrans();
		//遍历查到的人
		foreach($res as $k => $v){
			//每次轮到一人时开始查找当前的市价，该次交易量和涨价
			$param = M('param') -> field('param1,param8_1,param8_2,param13') -> where('id=%d',[1]) -> find(); 
			//还需要多少认购积分
			$xuyao = M() -> query('select points_num1 from zx_k_log where k_id=(select max(k_id) from zx_k_log)');
			$xuyaorengou = $xuyao[0]['points_num1'] * $param['param1'];
			//判断认购积分是否大于还需要的认购积分
			if($xuyaorengou<$v['user_money3']){			//如果剩余认购积分小于当前匹配人的认购积分，要拆分算
				//先获取当前价格下，该用户能匹配的认购积分，用该用户积分减去还剩余的认购积分
				$shengyu = $v['user_money3'] - $xuyaorengou;
				//前半部，该用户能获得的E积分
				$option_num = $xuyaorengou / $param['param1'];
				$option1 = $v['option_num'] + $option_num;
				if($option1>$v['max_amount']){
					$option1 = $v['max_amount'];
				}
				//将该用户改变值加入到数组中
				$data = ['option_num'=>$option1,'user_money3'=>0];
				//更新该用户数据
				$res2 = $m -> data($data) -> where('user_id=%d',[$v['user_id']]) -> save();
				//封装前台日志
					$user_log = M('account_log');
					$us_log['user_id'] = $v['user_id'];
					$us_log['user_money3'] = - $xuyaorengou;
					$us_log['option_num'] = $option_num;
					$us_log['change_time'] = time();
					$us_log['change_type'] = 60;
					$us_log['change_desc'] = '自动排队购买会员出售e积分';					
					$res3 = $user_log -> add($us_log);

				if($res2<1||$res3<1){
					$m -> rollback();
					$this -> error('拆分前部分匹配时失败');
				}
				
				//该轮交易已经完毕，开始涨价
				$param1 = $param['param1'] + $param['param8_2'];
				//算出可出售E积分
				$selle = M('users') -> field('user_id,option_num') -> where('option_num>%s',[0]) -> select();
				// dump($selle);die;
				foreach($selle as $a => $b){
					M() -> execute('update zx_users set sell_option_num = '.($b['option_num']*$param['param13']/100).' where user_id=%d',$b['user_id']);
					

				}

				//更新param数据表
				M('param') -> data(['param1'=>$param1]) -> where('id=%d',[1]) -> save();
				//在zx_k_log下插入一条新数据，表示涨价
				M('k_log') -> data(['k_money'=>$param1,'k_datetime'=>time(),'points_num1'=>$param['param8_1'],'points_num2'=>$param['param8_1']]) -> add();

				//第二部分开始
				//算出该用户剩余认购积分在涨价够得到的E积分
				$option_num = $shengyu / $param1;
				//找到当前用户上半部匹配后的的E积分
				$hou = M('users') -> field('option_num') -> where('user_id=%d',[$v['user_id']]) -> find();
				// 如果之前的E积分已经封顶了
				if($hou['option_num'] == $v['max_amount']){
					//放过
					$res2 = true;
				}else{
					//算出要得的E积分
					$option1 = $hou['option_num'] + $option_num;
					if($option1>$v['max_amount']){
						$option1 = $v['max_amount'];
					}
					//将后半部E积分加入数组
					$data = ['option_num'=>$option1];
					//更新该用户的E积分
					$res2 = $m -> data($data) -> where('user_id=%d',[$v['user_id']]) -> save();
						//封装前台日志
					$user_log = M('account_log');
					$us_log['user_id'] = $v['user_id'];
					$us_log['user_money3'] = -$shengyu;
					$us_log['option_num'] = $option_num;
					$us_log['change_time'] = time();
					$us_log['change_type'] = 60;
					$us_log['change_desc'] = '自动排队购买会员出售e积分';					
					$res4 = $user_log -> add($us_log);
					if($res2>0 && $res4){
						$m -> commit();
					}else{
						$m -> rollback();
						$this -> error('拆分后部分匹配时失败');
					}
				}
				
				//查到zx_k_log的最后ID
				$jian = M() -> query('select points_num1 from zx_k_log where k_id=(select max(k_id) from zx_k_log)');
				//算出新价格剩余E积分
				$param['param8_1'] = $jian[0]['points_num1'] - $option;
				M('k_log') -> data(['k_money'=>$param1,'k_datetime'=>time(),'points_num1'=>$param['param8_1']]) -> save();
			}else{				//如果剩余认购积分大于要匹配人的认购积分
				// 用剩余的认购积分减去当前匹配的认购积分
				$xuyaorengou = $xuyaorengou - $v['user_money3'];
				//算得还需要的E积分数,即剩余的认购积分/当前市价
				$shengyuejf = $xuyaorengou / $param['param1'];
				//算得该用户要得到的E积分数量，即认购积分/当前市价
				$option_num = $v['user_money3'] / $param['param1'];

				//算出该用户要匹配完后加多少E积分
				$option1 = $v['option_num']+$option_num;
				// echo $option1;die;
				if($option1 > $v['max_amount']){
					$option1 = $v['max_amount'];
				}
				//将该用户认购积分清零，改变E积分数量
				$data = ['user_money3'=>0,'option_num'=>$option1];
				$res2 = $m -> data($data) -> where('user_id=%d',[$v['user_id']]) -> save();
				if($v['option_num'] == 0){
					M() -> execute('update zx_users set sell_option_num = '.($option1*$param['param13']/100).' where user_id = '.$v['user_id']);
					// echo M() -> _SQL();die;
				}
				//封装前台日志
					$user_log = M('account_log');
					$us_log['user_id'] = $v['user_id'];
					$us_log['user_money3'] = -$v['user_money3'];
					$us_log['option_num'] = $option1;
					$us_log['change_time'] = time();
					$us_log['change_type'] = 60;
					$us_log['change_desc'] = '自动排队购买会员出售e积分';					
					$res5 = $user_log -> add($us_log);
				//获取当前价格表中，最新数据的ID
				$lastid = M('k_log') -> field('k_id') -> order('k_id desc') -> find();
				//更新该表数据
				$gaibian = M('k_log') -> data(['k_datetime'=>time(),'points_num1'=>$shengyuejf]) -> where(['k_id'=>$lastid['k_id']]) -> save();
			}
			
		}
		if($res2>0 && $res5>0){
			$m -> commit();
		}else{
			$m -> rollback();
			$this -> error('匹配失败');
		}
		//封装后台日志
			$admin_log = M('admin_log');
			$ad_log['user_name'] = $_SESSION['admin']['user_name'];
			$ad_log['log_time'] = time();
			$ad_log['user_id'] = $_SESSION['admin']['user_id'];
			$ad_log['log_info'] = '匹配认购积分'.I('post.renshu').'人';
			$ad_log['ip_address']= get_client_ip();
			 $admin_log -> add($ad_log);
		$this -> success('匹配成功');
	}

	public function ppejf(){
		//待匹配人数
		$count = M('market') -> where(['change_type'=>'option_num','status'=>0]) -> count();
		//分页
		$Page = new Page($count,50);
		$show = $Page -> show();
		//认购积分总数
		// $peo = M('users') -> field('sum(user_money3) as user_money3') -> find();
		//当前剩余积分数量
		// $mod = new Model();
		// $price = $mod -> query('select points_num1 from zx_k_log where k_id=(select max(k_id) from zx_k_log)');
		// $points_num1 = $price[0]['points_num1'];
		//预计和涨价
		// $res2 = M('param') -> field('param1,param8_2') -> where('id=%d',[1]) -> find();
		// $tishi = $res2['param1']*$points_num1;
		// $zhangjia = $res2['param8_2'];
		//市场剩余e积分数量
		$market = M('market') -> field('sum(sell_num) as sell_num') -> where(['change_type'=>'option_num','status'=>0]) -> find();
		//市场累计出售e积分总数量
		$all = M('market') -> field('sum(sell_num) as sell_num') -> where(['change_type'=>'option_num','status'=>3,'sell_user_id'=>['neq',0]]) -> find();
		$s_all = $all['sell_num'];
		//查询待匹配E积分
		$market1 = M('market') -> field('mk_id,sell_user_name,sell_num,sell_time,sell_user_id') -> where(['change_type'=>'option_num','status'=>0]) -> limit($Page->firstRow.','.$Page->listRows) -> select();
		// $this -> assign('tishi',$tishi);
		$this -> assign('market',$market);
		// $this -> assign('points_num1',$points_num1);
		// $this -> assign('zhangjia',$zhangjia);
		// $this -> assign('peo',$peo);
		// $this -> assign('gujia',$res2['param1']);
		$this -> assign('url',$show);
		$this -> assign('count',$count);
		$this -> assign('market1',$market1);
		$this -> assign('s_all',$s_all);
		$this -> display();
	}

	public function actejfid(){
		// echo I('get.id');die;
		//当前价格
		$res2 = M('param') -> field('param1,param4,param7,param5,param6') -> where('id=%d',[1]) -> find();
		$gujia = $res2['param1'];
		//扣税后的积分
		$jifen = I('get.sell_num') * (1-$res2['param4']/100);
		//返回的商城积分
		$user_money4 = $jifen * $res2['param7']/100 * $res2['param1'];
		//返回的E积分
		$option_num = $jifen * $res2['param5']/100;
		//返回的现金积分
		$user_money1 = $jifen * $res2['param6']/100 * $gujia;
		//将现金积分和商城积分加到数组以备UPDATE
		// $data = ['user_money4'=>$user_money4,'user_money1'=>$user_money1];
		//当前处理匹配的E积分
		$user = M('users') -> field('user_name,option_num2,user_money4,user_money1,option_num,inviter_id,max_amount,sell_option_num,out_amount') -> join('zx_user_type on zx_users.user_type=zx_user_type.id') -> where('user_id=%d',[I('get.id')]) -> find();
		$sellusername = $user['user_name'];
		// dump($user);die;
		//加入现有商城积分
		$data['user_money4'] = $user['user_money4'] + $user_money4;
		//加入现金积分
		$data['user_money1'] = $user['user_money1'] + $user_money1;
		//加入E积分
		$data['option_num'] = $user['option_num'] + $option_num;
		$data['option_num2'] = $user['option_num2'] + I('get.sell_num');
		// if($option_num>$user['max_amount']){
		// 	$data['option_num'] = $user['option_num'];
		// }
		// //判断是否要出局
		// if($user['sell_option_num']>=$user['out_amount']){
		// 	M() -> execute('update zx_users set is_out = 0 where user_id = %d',I('get.id'));
		// }

		//判断是否要出局
		$zuida = $data['option_num'] + $user['option_num2'];
		if($zuida>=$user['out_amount']){
			M() -> execute('update zx_users set is_out = 0,option_num2=0 where user_id = %d',I('get.id'));
		}

		// $data['option_num'] =$data['option_num'] - $user['option_num'];

		if($data['option_num']>=$user['max_amount']){
			$data['option_num'] = $user['max_amount'];
			
		}




		//开启事务
		M('users') -> startTrans();
		//更新当前用户数据
		$res1 = M('users') -> data($data) -> where('user_id=%d',[I('get.id')]) -> save();
		$res2 = M('market') -> data(['status'=>'3']) -> where('mk_id=%d',[I('get.mkid')]) -> save();
		if(!$res2){
			M('users') -> rollback();
			$this -> error('改变状态失败');
		}
		// echo $user['tree_id'];die;
		$res2 = M('param') -> field('param1,param4,param7,param5,param6') -> where('id=%d',[1]) -> find();
		if($res1>0){
			//获取最高能拿多少层
			$level = M('user_type') -> field('jy_level') -> select(); 
			foreach($level as $k=>$v){
				$arr[] = $v['jy_level'];
			}
			rsort($arr);
			$max = $arr[0];
			//dump($max);die;
			for($i=1;$i<=$max;$i++){
				if(empty($user['inviter_id']) || $user['inviter_id'] == 0){
					$res = true;
				}else{
					$user1 = $user['inviter_id'];
					if($user1 == 3000001){
						$res = true;
					}else{
						$user = M('users') -> field('user_name,pay_points4,jy_level,jy_percent,user_money4,user_money1,inviter_id') -> join('zx_user_type on zx_users.user_type=zx_user_type.id') -> where('user_id=%d',[$user1]) -> find();
						if($i<=$user['jy_level']){
							//上一代要拿的交易奖
							
					 		$points4 = $jifen * $res2['param6']/100 * $user['jy_percent'] / 100*$res2['param1'];
					 	
					 		$pay_points4_1 = $user['pay_points4'] + $points4;
					 		//现金积分
					 		$money1_1 = $user['user_money1'] + $points4;
					 		//建立数组存放
					 		$data1 = ['user_money1'=>$money1_1,'pay_points4'=>$pay_points4_1];
					 		//更新数据
					 
					 		$res = M('users') -> data($data1) -> where('user_id="%d" ',[$user1]) -> save();
					 		//判断结果
					 		$parm6 = $res2['param6'];
					 		$parm1 = $res2['param1'];
					 		//插入交易奖
									$user_log=M('account_log');
									$us_log_jy['user_id'] = $user1;
									$us_log_jy['about_user_name'] = I('get.id');
									$us_log_jy['user_money1'] = $points4;			
									$us_log_jy['pay_points4'] = $points4;			
									$us_log_jy['change_time'] = time();
									$us_log_jy['change_type'] = 99;
									$us_log_jy['change_desc'] = '第'.$i.'代交易奖[会员:('.$sellusername.')出售]税后'.$jifen.'*'.$parm6.'%*'.$parm1.'*'.$user['jy_percent'] .'%='.$points4;			
									$res4 = $user_log -> add($us_log_jy);
									
					 		if(!$res){
					 			M('users') -> rollback();
					 			$this -> error('推荐人匹配失败，请重新匹配');
					 		}
						}else{
							$res = true;
						}
					}
					
				}
				
			}
			//封装后台日志	
			$admin_log = M('admin_log');
			$ad_log['user_name'] = $_SESSION['admin']['user_name'];
			$ad_log['log_time'] = time();
			$ad_log['user_id'] = $_SESSION['admin']['user_id'];
			$ad_log['log_info'] = '匹配e积分人数为1';
			$ad_log['ip_address']= get_client_ip();
			$res8 = $admin_log -> add($ad_log);
			//封装前台日志三条
			//商城积分获取日志
			$user_log=M('account_log');
			$us_log['user_id'] = I('get.id');
			$us_log['user_money4'] = $user_money4;			
			$us_log['change_time'] = time();
			$us_log['change_type'] = 60;
			$p7 = $res2['param7']/100;
			$us_log['change_desc'] = '出售'.I('get.sell_num').'E积分返还'.$jifen.'*'.$p7.'*'.$res2['param1'].'='.$user_money4.'商城积分';			
			$res3 = $user_log -> add($us_log);			
			//现金积分日志
			$us_log['user_money4'] = 0;
			$us_log['user_id'] = I('get.id');
			$us_log['user_money1'] = $user_money1;			
			$us_log['change_time'] = time();
			$us_log['change_type'] = 60;
			$p6 = $res2['param6']/100;
			$us_log['change_desc'] = '出售'.I('get.sell_num').'E积分返还'.$jifen.'*'.$p6.'*'.$gujia.' = '.$user_money1.'现金积分';			
			$res6 = $user_log -> add($us_log);
			//现金积分日志
			$us_log['user_money4'] = 0;
			$us_log['user_money1'] = 0;
			$us_log['user_id'] = I('get.id');
			$us_log['option_num'] = $option_num;			
			$us_log['change_time'] = time();
			$us_log['change_type'] = 60;
			$p5 = $res2['param5']/100;
			$us_log['change_desc'] = '出售'.I('get.sell_num').'E积分返还'.$jifen.'*'.$p5.'= '.$option_num.'E积分';			
			$res5 = $user_log -> add($us_log);
			
			if($res3>0 && $res6>0 && $res5>0 && $res8>0){
				M('users') -> commit();
				$this -> success('匹配成功');
			}else{
				$this -> error('插入前台,或后台日志出错');
			}	
			
		}else{
			M('users') -> rollback();
			$this -> error('匹配当前失败');
		}
	}
	
	//批量匹配E积分
	public function actejfrs(){
		//获取所有匹配E积分人数
		$market1 = M('market') -> field('mk_id,sell_user_name,sell_num,sell_time,sell_user_id') -> where(['change_type'=>'option_num','status'=>0]) -> limit(I('post.renshu')) -> select();
		//获取当前市价
		$res2 = M('param') -> field('param1,param4,param7,param5,param6') -> where('id=%d',[1]) -> find();
		$gujia = $res2['param1'];

		foreach($market1 as $k => $v){
			//扣税后的积分
			$jifen = $v['sell_num'] * (1-$res2['param4']/100);
			//返回的商城积分
			$user_money4 = $jifen * $res2['param7']/100 * $res2['param1'];
			//返回的E积分
			$option_num = $jifen * $res2['param5']/100;
			//返回的现金积分
			$user_money1 = $jifen * $res2['param6']/100 * $gujia;
			//当前处理匹配的E积分
			$user = M('users') -> field('user_name,user_money4,user_money1,option_num,inviter_id,max_amount,out_amount,sell_option_num') -> join('zx_user_type on zx_users.user_type=zx_user_type.id') -> where('user_id=%d',[$v['sell_user_id']]) -> find();
			$sellusername = $user['user_name'];
			// dump($user);die;
			//加入现有商城积分
			$data['user_money4'] = $user['user_money4'] + $user_money4;
			//加入现金积分
			$data['user_money1'] = $user['user_money1'] + $user_money1;
			//加入E积分
			$data['option_num'] = $user['option_num'] + $option_num;
			$data['option_num2'] = $user['option_num2'] + $v['sell_num'];




			//判断是否要出局
			$zuida = $data['option_num'] + $user['option_num2'];
			if($zuida>=$user['out_amount']){
				M() -> execute('update zx_users set is_out = 0,option_num2=0 where user_id = %d',$v['sell_user_id']);
			}

			// $data['option_num'] =$data['option_num'] - $user['option_num'];

			if($data['option_num']>=$user['max_amount']){
				$data['option_num'] = $user['max_amount'];
				
			}




			// if($option_num>$user['max_amount']){
			// 	$data['option_num'] = $user['option_num'];
			// }
			// //判断是否要出局
			// if($user['sell_option_num']>=$user['out_amount']){
			// 	M() -> execute('update zx_users set is_out = 0 where user_id = %d',$v['sell_user_id']);
			// }


			M('users') -> startTrans();
			//更新当前用户数据
			$res1 = M('users') -> data($data) -> where('user_id=%d',[$v['sell_user_id']]) -> save();
			$res2 = M('market') -> data(['status'=>'3']) -> where('mk_id=%d',[$v['mk_id']]) -> save();
			if(!$res2){
				M('users') -> rollback();
				$this -> error('改变状态失败');
			}

			//封装前台日志三条
					//商城积分获取日志
					$user_log=M('account_log');
					$us_log['user_id'] = $v['sell_user_id'];
					$us_log['user_money4'] = $user_money4;			
					$us_log['change_time'] = time();
					$us_log['change_type'] = 60;
					$p7 = $res2['param7']/100;
					// dump($p7);die;
					$us_log['change_desc'] = '出售'.$v['sell_num'].'E积分返还'.$jifen.'*'. $p7.'*'.$res['param1'].'= '.$user_money4.'商城积分';			
					$res3 = $user_log -> add($us_log);
					//现金积分日志
					$us_log['user_money4'] = 0;
					$us_log['user_id'] = $v['sell_user_id'];
					$us_log['user_money1'] = $user_money1;			
					$us_log['change_time'] = time();
					$us_log['change_type'] = 60;
					$p5 = $res2['param5']/100;
					$us_log['change_desc'] = '出售'.$v['sell_num'].'E积分返还'. $jifen .'*'. $p5.'*'. $gujia.' = '.$user_money1.'现金积分';			
					$res4 = $user_log -> add($us_log);
					//现金积分日志
					$us_log['user_money4'] = 0;
					$us_log['user_money1'] = 0;
					$us_log['user_id'] = $v['sell_user_id'];
					$us_log['option_num'] = $option_num;			
					$us_log['change_time'] = time();
					$us_log['change_type'] = 60;
					$p6 = $res2['param6']/100;
					$us_log['change_desc'] = '出售'.$v['sell_num'].'E积分返还'.$jifen.'*'. $p6.'='.$option_num.'E积分';			
					$res5 = $user_log -> add($us_log);

					//封装后台日志	
					$admin_log = M('admin_log');
					$ad_log['user_name'] = $_SESSION['admin']['user_name'];
					$ad_log['log_time'] = time();
					$ad_log['user_id'] = $_SESSION['admin']['user_id'];
					$ad_log['log_info'] = '匹配e积分人数为'.I('post.renshu');
					$ad_log['ip_address']= get_client_ip();
					$res8 = $admin_log -> add($ad_log);

			if($res1>0){
				//获取最高能拿多少层
				$level = M('user_type') -> field('jy_level') -> select(); 
				foreach($level as $k=>$v){
					$arr[] = $v['jy_level'];
				}
				rsort($arr);
				$max = $arr[0];
				//获取当前市价
				$res2 = M('param') -> field('param1,param4,param7,param5,param6') -> where('id=%d',[1]) -> find();
				for($i=1;$i<=$max;$i++){
					if(empty($user['inviter_id']) || $user['inviter_id'] == 0){
						$res = true;
					}else{
						$user1 = $user['inviter_id'];
						if($user1 == 3000001){
							$res = true;
						}else{
							$user = M('users') -> field('user_name,pay_points4,jy_level,jy_percent,user_money4,user_money1,inviter_id') -> join('zx_user_type on zx_users.user_type=zx_user_type.id') -> where('user_id=%d',[$user1]) -> find();
							if($i<=$user['jy_level']){
								//上一代要拿的交易奖
						 		$points4 = $jifen * $res2['param6']/100 * $user['jy_percent'] / 100*$res2['param1'];
						 		$pay_points4_1 = $user['pay_points4'] + $points4;
						 		//现金积分
						 		$money1_1 = $user['user_money1'] + $points4;
						 		//建立数组存放
						 		$data1 = ['user_money1'=>$money1_1,'pay_points4'=>$pay_points4_1];
						 		//更新数据
						 		$res = M('users') -> data($data1) -> where('user_id=%d',[$user1]) -> save();
						 		//判断结果
						 		if(!$res){
						 			M('users') -> rollback();
						 			$this -> error('推荐人匹配失败，请重新匹配');
						 		}
						 		//插入交易奖
						 		$parm6 = $res2['param6'];
					 			$parm1 = $res2['param1'];
									$user_log=M('account_log');
									$us_log['user_id'] = $user1;
									$us_log['user_money1'] = $points4;			
									$us_log['pay_points4'] = $points4;			
									$us_log['change_time'] = time();
									$us_log['change_type'] = 99;
									$us_log['change_desc'] = '第'.$i.'代交易奖[会员:'.$sellusername.'出售]税后'.$jifen.'*'.$parm6.'%*'.$parm1.'*'.$user['jy_percent'].'%='.$points4;			
									$res4 = $user_log -> add($us_log);
							}else{
								$res = true;
							}
						}
						
					}
					
				}

				M('users') -> commit();
				$this -> success('匹配成功');
			}else{
				M('users') -> rollback();
				$this -> error('匹配当前失败');
			}
		}

	}
}
